package com.tzx.socketdemo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.WeakHashMap;

/**
 * Created by tanzhenxing
 * Date: 2016/10/10.
 * Description:
 */
public class TCPSocketClient {
    //服务端地址
    private String serverIp = "10.252.152.137";
    //服务端端口号
    private int serverPort = 9999;
    //套接字
    private Socket mSocket = null;
    //缓冲区读取
    private BufferedReader in = null;
    //字符打印
    private PrintWriter out = null;
    //tcp套接字
    private TcpSocketListener tcpSocketListener;
    //内容
    private String content = "";

    public TCPSocketClient(TcpSocketListener tcpSocketListener) {
        this.tcpSocketListener = tcpSocketListener;
    }

    public TCPSocketClient(String serverIp, int serverPort, TcpSocketListener tcpSocketListener) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        this.tcpSocketListener = tcpSocketListener;
    }

    public void startTcpSocketConnect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mSocket = new Socket(serverIp, serverPort);
                    in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true);
                    while (true) {
                        if (mSocket.isConnected()) {
                            if (!mSocket.isInputShutdown()) {
                                if ((content = in.readLine()) != null) {
                                    content += "\n";
                                    if (tcpSocketListener != null) {
                                        tcpSocketListener.callBackContent(content);
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void sendMessageByTcpSocket(String msg) {
        if (mSocket != null && mSocket.isConnected()) {
            if (!mSocket.isOutputShutdown() && out != null) {
                out.println(msg);
                if (tcpSocketListener != null) {
                    tcpSocketListener.clearInputContent();
                }
            }
        }
    }

    public interface TcpSocketListener {
        //回调内容
        void callBackContent(String content);
        //清除输入内容
        void clearInputContent();
    }
}
